/**
 * @file date-range
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import {findDOMNode} from 'react-dom';
import * as cx from 'classnames';
import './rich-text.scss';

export default class AceEditor extends PureComponent
{
  static propTypes = {
    className: PropTypes.string,
    onChange: PropTypes.func.isRequired
  };

  static defaultProps = {
    onChange: value => console.log(value),
    className: 'form-control ace-editor-control ',
    minLines: 10,
    maxLines: 30,
    width: '100%',
    height: '200px',
    mode: 'json'
  };

  constructor(props) {
    super(props);

    this.state = {
      AceEditor: null,
      focused: false
    };

    this.handleFocus = this.handleFocus.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
  }

  componentDidMount() {
    require(['react-ace', 'brace', 'brace/mode/json', 'brace/mode/javascript', 'brace/mode/jsx', 'brace/mode/css', 'brace/theme/github', './ace-hacker'], Component => {
      this.setState({
        AceEditor: Component.default
      })
    });
  }

  handleFocus() {
    this.setState({
      focused: true
    });
  }

  handleBlur() {
    this.setState({
      focused: false
    });
  }


  render() {
    const {
      className,
      onChange,
      value,
      minLines,
      maxLines,
      width,
      height,
      mode,
      name
    } = this.props;
    const AceEditor = this.state.AceEditor;
    const focused = this.state.focused;

    return (
      <div className={cx(className, {
        focus: focused
      })}>
        {AceEditor ? (
          <AceEditor
            name={name}
            mode={mode}
            theme="github"
            onChange={onChange}
            value={value}
            onFocus={this.handleFocus}
            onBlur={this.handleBlur}
            width={width}
            height={height}
            minLines={minLines}
            maxLines={maxLines}
            tabSize={2}
            showPrintMargin={false}
            editorProps={{$blockScrolling: true}}
          />
        ) : (
          <i className="fa fa-spinner fa-spin fa-2x" />
        )}
      </div>
    );
  }
}
